#!/usr/bin/env python
# -*- coding:utf-8 -*-
import json
import re
import pymongo
import requests


class Che168(object):
    QUERY_URL = 'http://m.che168.com/Evaluate/EvaCar.aspx?bid=%s&sid=%s&specid=%s&year=%s&month=%s&pid=%s&cid=%s&mileage=%s&type=1&classType=2'
    CHECK_RST_URL = 'http://m.che168.com/pinggu/eva_%s.html?type=2&pid=%s&hideHeadFoot=0&hideAdJump=0'
    # bid - 品牌(宝马/大众/...)
    # sid - 车款(宝马三系)
    # specid - 车型(2015款 316Li 手动型)
    # pid - 省份
    # cid - 城市

    def __init__(self, **kwargs):
        self.data = kwargs
        self.request = requests.Session()
        self.request.headers['User-Agent'] = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36'

    def build_query_url(self):
        return Che168.QUERY_URL % (
            self.data['bid'], self.data['sid'], self.data['specid'],
            self.data['year'], self.data['month'], self.data['pid'],
            self.data['cid'], self.data['mileage']
        )

    def get_url_content(self, url):
        return self.request.get(url).content

    def parse_msg_id(self, text):
        self.msg_id = re.findall(ur'message[\'"]:\[[\'"](\d+?)[\'"]', text)[0]

    def check_result(self):
        url = Che168.CHECK_RST_URL % (self.msg_id, self.data['pid'])
        content = self.get_url_content(url).decode('utf-8')
        self.pre_price = re.findall(ur'<p>该车评估价格：<b class="price">(.+?)万元</b></p>', content)[0]

    def process_price(self):
        price = re.split(ur'-', self.pre_price)
        self.min_price = float(price[0])
        self.max_price = float(price[1])

    def run(self):
        try:
            content = self.get_url_content(self.build_query_url())
            if '"error":"0"' not in content:
                return None
            self.parse_msg_id(content)
            self.check_result()
            self.process_price()
            return self.min_price, self.max_price
        except Exception, e:
            return None


def deal_car(arg):
    if arg == 'car/brand/' or arg == 'car/brand':
        return select_all_brand()
    elif re.match(ur'car/brand/\d+[/]?', arg):
        brand_id = re.findall(ur'car/brand/(\d+)[/]?', arg)[0]
        return select_model_by_brand(brand_id)
    elif re.match(ur'car/model/\d+[/]?', arg):
        model_id = re.findall(ur'car/model/(\d+)[/]?', arg)[0]
        return select_car_by_model(model_id)
    return ''


def search(cars, city, year, month, mileage):
    # return [search_price(car=car, city=city, year=year, month=month, mileage=mileage) for car in cars]
    result = []
    for index, car in enumerate(cars):
        if index >= 10:
            break
        result.append(search_price(car=car, city=city, year=year, month=month, mileage=mileage))
    return result


def search_price(**kwargs):
    for kw in kwargs:
        if not kwargs[kw]:
            raise HTTPError(400, '%s empty.' % kw)
    car_info = kwargs['car']
    city_info = kwargs['city']
    year = kwargs['year']
    month = kwargs['month']

    price = Che168(
        bid=car_info['brandId'],
        sid=car_info['modelId'],
        specid=car_info['_id'],
        pid=city_info['provId'],
        cid=city_info['_id'],
        year=year,
        month=month,
        mileage=kwargs['mileage']
    ).run()
    if not price:
        return None
    return {
        'min': price[0],
        'max': price[1],
        'unit': u'万元',
        'city': city_info['city'],
        'province': city_info['province'],
        'licenseTime': u'%d年%02d月' % (year, month),
        'mileage': kwargs['mileage'] + u'万公里',
        'brand': car_info['brand'],
        'model': car_info['model'],
        'carName': car_info['carName'],
    }

if __name__ == '__main__':
    Che168(bid='15', sid='66', specid='20155', pid='440000', cid='445100',
           year='2015', month='6', mileage='1.3').run()

